/**
 * 
 */
package org.ccay.core.util;

import java.util.HashSet;
import java.util.Set;

//import org.apache.neethi.builders.converters.Converter;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.core.convert.converter.ConverterRegistry;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.core.convert.support.ConversionServiceFactory;
import org.springframework.core.convert.support.DefaultConversionService;
import org.ccay.core.ioc.Ccay;

/**
 * 
 * Converter 辅助类，使用spring的converter框架
 * 
 * 主要用于数据类型转化。
 * 
 * 
 * 
 */
public final class ConverterUtil {

	private ConverterUtil() {

	}

	/**
	 * 数据转化服务
	 */
	private static ConversionService CONVERSION_SERVICE = new DefaultConversionService();

	static {
		// 初始化ConversionService
		Set<Object> beans = new HashSet<Object>();

		// 避免测试类出现异常
		if (Ccay.getContext() != null) {
			for (Class<?> type : new Class<?>[] { GenericConverter.class, /*Converter.class, TODO neethi依赖加入后放开*/ ConverterFactory.class }) {
				beans.addAll(Ccay.getContext().getBeansOfType(type).values());
			}
			ConversionServiceFactory.registerConverters(beans, (ConverterRegistry) CONVERSION_SERVICE);
		}
	}

	/**
	 * 数据转化
	 * 
	 * @param value
	 *            原始数据值
	 * @param clazz
	 * @return
	 */
	public static <T> T convert(Object value, Class<T> clazz) {
		return CONVERSION_SERVICE.convert(value, clazz);
	}

	/**
	 * 数据转化
	 * 
	 * @param value
	 *            原始数据值
	 * @param clazz
	 * @param def
	 *            默认值
	 * @return
	 */
	public static <T> T convert(Object value, Class<T> clazz, T def) {
		T result = CONVERSION_SERVICE.convert(value, clazz);
		return result != null ? result : def;
	}

	/**
	 * 
	 * 转化成boolean
	 * 
	 * @param value
	 * @return
	 */
	public static Boolean toBool(Object value) {
		return CONVERSION_SERVICE.convert(value, Boolean.class);
	}

	/**
	 * 
	 * 转化成String
	 * 
	 * @param value
	 * @return
	 */
	public static String toString(Object value) {
		return CONVERSION_SERVICE.convert(value, String.class);
	}

	/**
	 * 
	 * 转化成Integer
	 * 
	 * @param value
	 * @return
	 */
	public static Integer toInt(Object value) {
		return CONVERSION_SERVICE.convert(value, Integer.class);
	}

	/**
	 * 
	 * 转化成Long
	 * 
	 * @param value
	 * @return
	 */
	public static Long toLong(Object value) {
		return CONVERSION_SERVICE.convert(value, Long.class);
	}
}
